javascript algorithm exercise